import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:zmcy_flutter/controllers/discover_controller.dart';
import 'package:zmcy_flutter/pages/discover_page.dart';

import '../pages/video_list_page.dart';
import '../common/events.dart';
import '../common/routes.dart';
import '../pages/cartoons_page.dart';
import '../pages/message_page.dart';
import '../pages/mine_page.dart';
import '../pages/pipe_list_page.dart';
import '../service/auth_service.dart';

class HomeController extends GetxController {
  var selectedIndex = 0.obs;
  var backPressAllowed = false.obs;
  StreamSubscription? _logoutStreamSub;

  final pages = <Widget>[
    const PipeListPage(),
    const CartoonsPage(),
    const MessagePage(),
    const DiscoverPage(),
    const MinePage()
  ];

  @override
  void onInit() {
    super.onInit();
    FlutterNativeSplash.remove();
    _logoutStreamSub = eventBus.on<UserLogoutEvent>().listen((event) {
      selectedIndex.value = 0;
    });
  }

  @override
  void onClose() {
    _logoutStreamSub?.cancel();
    super.onClose();
  }

  void onItemTapped(int index, BuildContext context) {
    if (index == 2 || index == 4) {
      if ( Get.find<AuthService>().isLogIn == false) {
        Get.toNamed(Routes.LOGIN);
        return;
      }
    }
    selectedIndex.value = index;
  }

  Future<void> allowBackPress() async {
    backPressAllowed.value = true;
    await Future.delayed(const Duration(milliseconds: 2000));
    backPressAllowed.value = false;
  }
}
